<template>

</template>

<script>
import { mapActions, mapGetters } from "vuex"
export default {
  data() {
    return {
      beforeRouter: undefined
    }
  },
  computed: {
    ...mapGetters("seedActivityStatus", {
      seedActivity: "getSeedActivity",
      isSeedEntery: "getIsSeedEntery"
    }),
    ...mapGetters("contentStatus", {
      questionIndex: "getQuestionIndex",
      contentItem: "getContentItem",
    }),
      ...mapGetters("personalStatus",{
          userVip: "getUserVip"
      })
  },
  methods: {
    //加载绘本
    loadPicbook: async function (option) {
      const resultOption = $.extend({
        picbookId: undefined,
        beforeRouter: undefined
      }, option)
      this.beforeRouter = resultOption.beforeRouter
      this.setLoading({
        content: "正在加载绘本，请稍后。。。",
        isProgress: true,
        progressCount: 20,
        isBackground: true
      })
      const json = {
        deviceUuid: this.deviceUuid,
        picbookId: resultOption.picbookId,
        deviceWidth: screen.width,
        deviceHeight: screen.height,
        dpr: window.devicePixelRatio,
        isInSeedActivity: this.isSeedEntery
          // 如果为 false，表示是普通模式进入的绘本列表，返回 estimate.pageIdAndQuestionsMap
        // 如果为 true，表示是通过【活动 - 种子用户孵化】进入的绘本列表，返回 estimate.questions
      }
      const [data, err] = await this.awaitWarp(this.$post(this.api.picbook, json))
      if (err) {
        this.setPopup({
          content: "加载绘本失败，请检查网络",
          closeIsShow: false,
          callback: () => {
            this.setLoading({
              isShow: false
            })
          }
        })
        return
      }
      if (data) {
        this.setLoading({
          content: "正在加载绘本内容，请稍后。。。",
          isProgress: true,
          progressCount: 20,
          isBackground: true
        })
      }
        for (let i in this.userVip.picbookIdAndCodeMapWithFree){
            if(data.picbook.id === parseInt(i)){
                this.$set(data.picbook,'vipFreeType',this.userVip.picbookIdAndCodeMapWithFree[i])
            }
        }
        this.userVip.picbooksWithCharge.forEach(vItem =>{
            if(data.picbook.id === vItem){
                this.$set(data.picbook,'vipFreeType',0)
            }
        })
      this.setPicbookIndex(data.picbook)
      this.initPicbook(data.picbook)
    },
    //初始化绘本数据
    initPicbook: function (datas) {
      const imageUrls = []
      this.eachDescendentParameters({
        object: datas,
        onEach: (map, key, value) => {
          if (typeof value === 'string' && (value.indexOf("https") === 0) && (value.indexOf(".png") > -1 || value.indexOf(".jpg") > -1)) {
            imageUrls.push(value)
            if (this.isCdvfile()) {
              value = this.variable.IMG_URLTITLE + value.match(/com(\S*)/)[1]
            }
            map[key] = value
          }
        }
      })
      //保存状态
      this.setContentItem(datas.pages)
      this.setImageryItem(datas.imageries)
      this.setRoleItem(datas.roles)
      this.setRoleAwards(datas.roleAwards)
      this.setPicbookType(datas.type)
      this.setWord(datas.words)
      //判断是否为种子用户邀请  (或者小程序)
      if (this.isSeedEntery && datas.estimate.questions) {
        const seedIndex = this.contentItem[this.contentItem.length - 1].id,
          seedQuestionsMap = { [seedIndex]: datas.estimate.questions }
        this.setAssignment(seedQuestionsMap)
      } else {
        this.setAssignment(datas.estimate.pageIdAndQuestionsMap)
      }
      this.setPicbookAudio(datas.audio.pageIdAndAudioMap)
      if (datas.type === 'blueFox') this.setClues(datas.blueFox)
      if (datas.type === 'poem') this.setPoem(datas.poem)
      this.preload(imageUrls)
    },
    //缓存图片 本地缓存或浏览器缓存
    preload: function (Img) {
      let allImg = Img.filter(item => item)
      let count = 0
      if (!this.isCdvfile()) {
        for (let img of allImg) {
          let image = new Image()
          image.src = img
          image.onload = () => {
            count++
            // 计算图片加载的百分数，绑定到percent变量
            let percentNum = Math.floor((count / allImg.length) * 80) + 20
            if (percentNum === 100) {
              this.setLoading({
                content: "加载完成，请稍后。。。",
                isProgress: true,
                progressCount: percentNum,
                callback: () => {
                  this.beforeRouter ? this.$router.replace({ path: "/picbook", query: { beforeRouter: this.beforeRouter } }) : this.$router.replace({ path: "/picbook" })
                },
                isBackground: true
              })
            }
            else {
              this.setLoading({
                content: "正在加载绘本内容，请稍后。。。",
                isProgress: true,
                progressCount: percentNum,
                isBackground: true
              })
            }
          }
        }
      }
      else {
        document.addEventListener("deviceready", () => {
          window.LoadFeature.loadFiles({
            fileUrls: allImg,
            onStep: (finishedStep, totalStep) => {
              if (totalStep > 1) {
                this.setLoading({
                  content: "正在加载绘本内容，请稍后。。。",
                  isProgress: true,
                  progressCount: 40 + finishedStep * 10,
                  isBackground: true
                })
              }
              else {
                this.setLoading({
                  content: "正在加载绘本内容，请稍后。。。",
                  isProgress: true,
                  progressCount: 80,
                  isBackground: true
                })
              }
            },
            // 当上传完所有文件后，触发此方法
            onLoad: () => {
              this.setLoading({
                content: "加载完成，请稍后。。。",
                isProgress: true,
                progressCount: 100,
                callback: () => {
                  this.beforeRouter ? this.$router.replace({ path: "/picbook", query: { beforeRouter: this.beforeRouter } }) : this.$router.replace({ path: "/picbook" })
                },
                isBackground: true
              })
            },
            onError: function () { }
          })
        }, false)
      }
    },
    ...mapActions("picbookListStatus", ["setPicbookIndex"]),
    ...mapActions("mainStatus", ["setLoading", "setPopup"]),
    ...mapActions("contentStatus", ["setContentItem", "setPicbookType", "setPicbookAudio"]),
    ...mapActions("blueFoxStatus", ["setClues"]),
    ...mapActions("poemStatus", ["setPoem"]),
    ...mapActions("imageryStatus", ["setImageryItem"]),
    ...mapActions("roleStatus", ["setRoleItem", "setRoleAwards", "setDefaultRoleAwardSize"]),
    ...mapActions("wordStatus", ["setWord"]),
    ...mapActions("assignmentStatus", ["setAssignment"])
  }
}
</script>

<style>
</style>
